package com.roocon.design_pattern.chapter08_active_object;

import java.util.LinkedList;

public class WorkTaskQueue {
  private final static int MAX_TASKS_QUEUE_SIZE = 100;

  private final LinkedList<Task> tasksQueue;

  public WorkTaskQueue() {
    this.tasksQueue = new LinkedList<>();
  }

  public synchronized void put(Task task) {
    while (tasksQueue.size() >= MAX_TASKS_QUEUE_SIZE) {
      try {
        this.wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    this.tasksQueue.addLast(task);
    this.notifyAll();
  }

  public synchronized Task task(){
    while (tasksQueue.isEmpty()) {
      try {
        this.wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    Task task = tasksQueue.removeFirst();
    this.notifyAll();
    return task;
  }
}
